<?php
namespace app\admin\controller;
use think\Db;
class Base extends \think\Controller
{
    public $userinfo = [];
    public $sys = [];
    public function __construct(){
        parent::__construct();
        $this->_checkLogin();
        $this->_appConfig();
    }
    /**
     * 验证登录
     */
    private function _checkLogin(){
        //判断路由
        if(com_controller()=='publics')
            return;
        //判断登陆
        $adminUser = new \app\admin\model\AdminUser();
        $userinfo = $adminUser->isLogin();
        if( $userinfo ){
            $this->userinfo = $userinfo;
            $this->assign('userinfo', $this->userinfo);
            \my\G::set( $this->userinfo );
        }else{
            r(url("Publics/logOut"));
        }
    }
    /**
     * 项目配置赋值
     */
    private function _appConfig(){
        $sys = Db::name('sys')->column('value','keyword');
        $this->sys = $sys;
        $this->assign('sys',$sys);
        if(!$this->userinfo) return;

        //权限和菜单
        #用户所属部门
        $ids = array_filter(explode(',',$this->userinfo['department_ids']));

        #部门权限
        $power = Db::name('department')->field("power_ids")->where('id','in', $ids)->select();

        #cur为每个部门都禁止的权限id
        $cur = [];
        foreach ($power as $v) {
            $tmp = array_filter(explode(',',$v['power_ids']));
            if(empty($cur)){
                $cur = $tmp;
            }else{
                $cur = array_intersect($cur,$tmp);
            }
        }
        $menu = c('menu');
        $forbid_title = [];
        $forbid_url = [];

        if($cur){
            #禁止的权限
            $res = Db::name('power')->field("title,url")->where('id','in',$cur)->select();
            foreach ($res as $v) {
                $forbid_title[] = $v['title'];
                $forbid_url[] = array_filter(explode(',',$v['url']));
            }

            #计算菜单
            $menu = c('menu');
            foreach ($menu as $ftitle => $son) {
                foreach ($son as $stitle => $url) {
                    if(in_array($url, $forbid_url)){
                        unset($menu[$ftitle][$stitle]);
                    }
                }
            }
            #重新计算大标题
            foreach ($menu as $ftitle => $son) {
                if(empty($son)){
                    unset($menu[$ftitle]);
                }
            }
        }
        $this->assign('menu',$menu);

        //给权限设置session.  cookie会被串改
        //后面再修改

    }
}
